const express = require('express');
const router = express.Router();
const db = require('../../../../util/dbConfig/dbConfig')
const dateReplace = require('../../../../public/javascripts/timeFormat')

//单一新增
router.post('/single',async (req,res) => {
    let userInfo = req.session.userInfo
    //鉴权
    if(req.session.userInfo.admin === 1 || !req.session.userInfo) {
        return res.send({
            code: 3,
            msg: '您未登录或权限不够'
        })
    }
    //模拟数据
    /*let obj = {
        userName: '李四',
        ramNum: 1,
        ramArr: ['6'],
        ramPrice: 10,
        eweNum: 1,
        eweArr: ['2'],
        ewePrice: 15,
        totalPrice: 25,
        buyer: '王六',
        buyDate: '2021-12-15T15:01:02Z',
        buyPhone: '19763026514'
    }*/
    let {
        userName,   //牧户姓名(卖主)
        ramNum,     //公羊数
        ramArr,     //公羊编号数组
        ramPrice,     //公羊单价
        eweNum,     //母羊数
        eweArr,     //母羊编号数组
        ewePrice,   //母羊单价
        totalPrice, //总价
        buyer,      //买主姓名
        buyDate,    //购买日期
        buyPhone,   //买主手机号
        //以上参数都为必填项
        remark,     //备注
    } = req.body

    let arr = [
        userName,   //牧户姓名(卖主)
        ramNum,     //公羊数
        ramPrice,     //公羊单价
        eweNum,     //母羊数
        ewePrice,   //母羊单价
        totalPrice, //总价
        buyer,      //买主姓名
        buyDate,    //购买日期
        buyPhone,   //买主手机号
    ]
    //确保参数有值
    for(let i = 0; i<arr.length; i++){
        if(arr[i] === '' || arr[i] === undefined){
            return res.send({
                code: 1,
                msg: '参数缺失'
            })
        }
    }
    //确保是本人操作
    if(userName !== userInfo.user){
        return res.send({
            code: 1,
            msg: '非本人不可操作，如果有疑问请检查输入的姓名是否正确'
        })
    }
    //确保羊只数量不全为0
    if(ramNum === 0 && eweNum === 0){
        return res.send({
            code: 1,
            msg: '羊只数不可全为零'
        })
    }
    //确保数组长度与羊只数量相等
    if(ramNum !== ramArr.length || eweNum !== eweArr.length){
        return res.send({
            code: 1,
            msg: '羊只数量与输入的羊只编号不相等，请确定再试'
        })
    }
    //时间格式化
    buyDate = await dateReplace(buyDate,res)
    //手机号数字类型转换
    buyPhone = Number(buyPhone)
    //待修改的参数
    let salesSqlArr = [
        buyer,      //买主姓名
        buyPhone,   //买主手机号
        buyDate,    //购买日期
        eweNum,     //母羊数
        ewePrice,   //母羊单价
        ramNum,     //公羊数
        ramPrice,     //公羊单价
        totalPrice, //总价
    ]
    try{
        //是否重复添加
        let checkAddSql = `select * from market where 
         BUYER_NAME=?
         and BUYER_PHONENUM=?
         and BUR_DATE=?
         and SHEEP_NUMBER=?
         and SHEEP_PRICE=?
         and RAM_NUMBER=?
         and RAM_PRICE=?
         and TOTAL_PRINCES=?`
        let checkAddResult = await db.SySqlConnect(checkAddSql,salesSqlArr)
        if(checkAddResult.length !== 0){
            return res.send({
                code: 1,
                msg: `重复添加，已有${checkAddResult.length}条`
            })
        }
        //查询卖主是不是该系统用户
        let buyerFindSql = `select ID,PHONENUM from user where NAME='${buyer}'`
        let buyerFindResult = await db.SySqlConnect(buyerFindSql,[])
        if(buyerFindResult.length === 0){
            //卖主不是该系统用户

            //查找排序最后的订单编号
            let salesIdSql = `SELECT ID FROM market order by ID desc`
            let salesIdResult = await db.SySqlConnect(salesIdSql,[])
            if(salesIdResult === 0){
                return res.send({
                    code: 4,
                    msg: '服务器错误，请稍后再试'
                })
            }
            //获取下一条销售信息的id
            let salesId = salesIdResult[0]['ID'] + 1
            //公羊添加销售订单编号
            if(ramArr.length !==0){
                for(let j =0; j<ramArr.length; j++){
                    let ramReplaceBuyerSql =  `update sheep set sold_id=${salesId} where ID=${ramArr[j]} and SEX=1 `
                    let ramReplaceBuyerResult = await db.SySqlConnect(ramReplaceBuyerSql,[])
                    if(ramReplaceBuyerResult.affectedRows === 0 ){
                        return res.send({
                            code: 2,
                            msg: `添加订单编号${salesId}到${ramArr[j]}失败`
                        })
                    }
                }
            }
            //母羊添加销售订单编号
            if(eweArr.length !==0){
                for(let j =0; j<eweArr.length; j++){
                    let eweReplaceBuyerSql =  `update sheep set sold_id=${salesId} where ID=${eweArr[j]} and SEX=2 `
                    let eweReplaceBuyerResult = await db.SySqlConnect(eweReplaceBuyerSql,[])
                    if(eweReplaceBuyerResult.affectedRows === 0 ){
                        return res.send({
                            code: 2,
                            msg: `添加订单编号${salesId}到${eweArr[j]}失败`
                        })
                    }
                }
            }
        }else {
            //卖主是该系统用户

            //手机号与卖主不匹配

            if(Number(buyerFindResult[0]['PHONENUM']) !== buyPhone){
                return res.send({
                    code: 1,
                    msg: '手机号与卖主手机号不同，请检查输入的手机号是否正确'
                })
            }
            //转移公羊到卖主户下
            if(ramArr.length !==0){
                for(let j =0; j<ramArr.length; j++){
                    let ramReplaceBuyerSql =  `update sheep set USER_ID=${buyerFindResult[0]['ID']} where ID=${ramArr[j]} and SEX=1 `
                    let ramReplaceBuyerResult = await db.SySqlConnect(ramReplaceBuyerSql,[])
                    if(ramReplaceBuyerResult.affectedRows === 0 ){
                        return res.send({
                            code: 2,
                            msg: `添加${ramArr[j]}失败`
                        })
                    }
                }
            }
            //转移母羊到卖主户下
            if(eweArr.length !==0){
                for(let j =0; j<eweArr.length; j++){
                    let eweReplaceBuyerSql =  `update sheep set USER_ID=${buyerFindResult[0]['ID']} where ID=${eweArr[j]} and SEX=2 `
                    let eweReplaceBuyerResult = await db.SySqlConnect(eweReplaceBuyerSql,[])
                    if(eweReplaceBuyerResult.affectedRows === 0 ){
                        return res.send({
                            code: 2,
                            msg: `添加${eweArr[j]}失败`
                        })
                    }
                }
            }
        }
        //添加销售订单
        let salesSql1 = `insert into market (
        BUYER_NAME,
        BUYER_PHONENUM,
        BUR_DATE,
        SHEEP_NUMBER,
        SHEEP_PRICE,
        RAM_NUMBER,
        RAM_PRICE,
        TOTAL_PRINCES
        `
        let salesSql2  //确定有remark的sql
        let salesSql3 = ' ' + 'values(?,?,?,?,?,?,?,?'  //sql后面一部分
        if(remark !== null ){
            //如果有remark，拼接sql
            salesSql2 = salesSql1 + ',REMARK)' + salesSql3 + `,${remark})`
        }
        //如果没有remark，拼接sql
        salesSql2 = salesSql1 + ')' + salesSql3 + ')'

        let salesResult = await db.SySqlConnect(salesSql2,salesSqlArr)
        if(salesResult.affectedRows === 1){
            return res.send({
                code: 0,
                msg: `添加成功,转移到${buyer},公羊${ramNum}只,母羊${eweNum}只`
            })
        }else{
            return res.send({
                code: 2,
                msg: '添加失败'
            })
        }
    }catch (e) {
        console.log(e);
        return res.send({
            code: 4,
            msg: '服务器错误，请稍后再试'
        })
    }

})

module.exports = router
